package com.example.zm_fanjiantao.web.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.example.zm_fanjiantao.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
public class Upload {

    @Value(value = "${upload.path}")
    private String uplaodPath;

    @Value(value = "${server.port}")
    private String port;

    @PostMapping("/uplaod")
    public Result upload(@RequestParam MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(fileName);

        //年月日当前时间时间戳uuid
        String url = DateUtil.today()+"/"+IdUtil.randomUUID()+"."+suffix;

        String filePath = uplaodPath+url;

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            FileUtil.writeFromStream(inputStream,filePath);
            String resultUrl = "//"+NetUtil.getLocalhostStr()+":"+port+"/files/"+url;
            Result result = new Result(200,"上传成功",resultUrl);
            return  result;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  Result.fail();

    }
}
